﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Strom.Core.Network;
using Strom.Server.IO;
using Strom.Core.Network.Packets;

namespace Strom.Server.Network
{
    public static class Parser
    {
        static readonly Dictionary<byte, IPacket> RegisteredPackets = new Dictionary<byte, IPacket>(); 

        public static void RegisterNewClientOnParser(BaseClient client)
        {
            ServerConsole.WriteSpecialMessage("Client connecté " + client, ServerConsole.MessageType.Event);
            ServerDatas.Server.OnlinePlayers++;
            client.Tag = ServerDatas.Server;
            client.PacketReceived += client_PacketReceived;
            client.ClientDisconnected += client_ClientDisconnected;
        }

        static void client_ClientDisconnected(BaseClient client)
        {
            ServerConsole.WriteSpecialMessage("Client déconnecté " + client, ServerConsole.MessageType.Event);
            ServerDatas.Server.OnlinePlayers--;
            client.PacketReceived -= client_PacketReceived;
            client.ClientDisconnected -= client_ClientDisconnected;
        }

        static void client_PacketReceived(BaseClient client, Packet packet)
        {
            if(!RegisteredPackets.ContainsKey(packet.ID))
            {
                ServerConsole.WriteSpecialMessage("Packet inconnu " + packet, ServerConsole.MessageType.Warning);
                return;
            }

            RegisteredPackets[packet.ID].Unpack(client,packet);
        }

        public static void RegisterPackets()
        {
            RegisteredPackets.Add(LoginRequestPacket.ID, new LoginRequestPacket());
            RegisteredPackets.Add(CreateCharacterRequestPacket.ID, new CreateCharacterRequestPacket());
        }
    }
}
